package com.liuguangqiang.cookie;


import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;

import java.io.IOException;

/**
 * Created by Eric on 2017/3/2.
 */
final class Cookie extends DirectionalLayout {
    public static final String TAG = "Cookie";

    private AnimatorProperty slideInAnimation;
    private AnimatorProperty slideOutAnimation;

    private DirectionalLayout layoutCookie;
    private Text tvTitle;
    private Text tvMessage;
    private Image ivIcon;
    private Text btnAction;
    private Image btnActionWithIcon;
    private long duration = 2000;
    private int layoutGravity = LayoutAlignment.BOTTOM;

    Cookie(final Context context) {
        this(context, null);
    }

    Cookie(final Context context, final AttrSet attrs) {
        this(context, attrs, null);
    }

    Cookie(final Context context, final AttrSet attrs, final String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews(context, attrs);
    }

    public int getLayoutGravity() {
        return layoutGravity;
    }

    private void initViews(Context context, AttrSet attrs) {
        LayoutScatter.getInstance(context).parse(ResourceTable.Layout_layout_cookie, this, true);

        layoutCookie = (DirectionalLayout) findComponentById(ResourceTable.Id_cookie);
        tvTitle = (Text) findComponentById(ResourceTable.Id_tv_title);
        tvMessage = (Text) findComponentById(ResourceTable.Id_tv_message);
        ivIcon = (Image) findComponentById(ResourceTable.Id_iv_icon);
        btnAction = (Text) findComponentById(ResourceTable.Id_btn_action);
        btnActionWithIcon = (Image) findComponentById(ResourceTable.Id_btn_action_with_icon);
//        initDefaultStyle(context, attrs);
    }


    /**
     * Init the default text color or background color. You can change the default style by set the
     * Theme's attributes.
     * <pre>
     *  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
     *          <item name="cookieTitleColor">@color/default_title_color</item>
     *          <item name="cookieMessageColor">@color/default_message_color</item>
     *          <item name="cookieActionColor">@color/default_action_color</item>
     *          <item name="cookieBackgroundColor">@color/default_bg_color</item>
     *  </style>
     * @param context
     * @param attrs
     */
    private void initDefaultStyle(Context context, AttrSet attrs) {
        if (attrs.getAttr("cookieTitleColor") != null && attrs.getAttr("cookieTitleColor").isPresent()) {
            Color cookieTitleColor = attrs.getAttr("cookieTitleColor").get().getColorValue();
            Color titleColor = ThemeResolver.getColor(cookieTitleColor, Color.WHITE);
            tvTitle.setTextColor(titleColor);
        }
        if (attrs.getAttr("cookieMessageColor") != null && attrs.getAttr("cookieMessageColor").isPresent()) {
            Color cookieMessageColor = attrs.getAttr("cookieMessageColor").get().getColorValue();
            Color messageColor = ThemeResolver.getColor(cookieMessageColor, Color.WHITE);
            tvMessage.setTextColor(messageColor);
        }
        if (attrs.getAttr("cookieActionColor") != null && attrs.getAttr("cookieActionColor").isPresent()) {
            Color cookieActionColor = attrs.getAttr("cookieActionColor").get().getColorValue();
            Color actionColor = ThemeResolver.getColor(cookieActionColor, Color.WHITE);
            btnAction.setTextColor(actionColor);
        }
        if (attrs.getAttr("cookieBackgroundColor") != null && attrs.getAttr("cookieBackgroundColor").isPresent()) {
            Color cookieBackgroundColor = attrs.getAttr("cookieBackgroundColor").get().getColorValue();
            Color backgroundColor = ThemeResolver.getColor(cookieBackgroundColor, ResourceTable.Color_default_bg_color);
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setRgbColor(RgbColor.fromArgbInt(backgroundColor.getValue()));
            layoutCookie.setBackground(shapeElement);
        }
    }

    public void setParams(final CookieBar.Params params) {
        if (params != null) {
            duration = params.duration;
            layoutGravity = params.layoutGravity;

            //Icon
            if (params.iconResId != 0) {
                ivIcon.setVisibility(VISIBLE);
                ivIcon.setImageElement(ResourceUtils.getDrawable(getContext(), params.iconResId));
            }

            //Title
            if (!TextUtils.isEmpty(params.title)) {
                tvTitle.setVisibility(VISIBLE);
                tvTitle.setText(params.title);
                if (params.titleColor != 0) {
                    tvTitle.setTextColor(ThemeResolver.getColor(params.titleColor));
                }
            }

            //Message
            if (!TextUtils.isEmpty(params.message)) {
                tvMessage.setVisibility(VISIBLE);
                tvMessage.setText(params.message);
                if (params.messageColor != 0) {
                    tvMessage.setTextColor(ThemeResolver.getColor(params.messageColor));
                }

                if (TextUtils.isEmpty(params.title)) {
                    DirectionalLayout.LayoutConfig layoutParams = (DirectionalLayout.LayoutConfig) tvMessage
                            .getLayoutConfig();
                    layoutParams.setMarginTop(0);
                }
            }

            //Action
            if ((!TextUtils.isEmpty(params.action) || params.actionIcon != 0)
                    && params.onActionClickListener != null) {
                btnAction.setVisibility(VISIBLE);
                btnAction.setText(params.action);
                btnAction.setClickedListener(new ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        params.onActionClickListener.onClick();
                        dismiss();
                    }
                });

                //Action Color
                if (params.actionColor != 0) {
                    btnAction.setTextColor(ThemeResolver.getColor(params.actionColor));
                }
            }

            if (params.actionIcon != 0 && params.onActionClickListener != null) {
                btnAction.setVisibility(HIDE);
                btnActionWithIcon.setVisibility(VISIBLE);
                btnActionWithIcon.setImageElement(ResourceUtils.getDrawable(getContext(), params.actionIcon));
                btnActionWithIcon.setClickedListener(new ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        params.onActionClickListener.onClick();
                        dismiss();
                    }
                });
            }

            //Background
            if (params.backgroundColor != 0) {
                ShapeElement shapeElement = new ShapeElement();
                shapeElement.setRgbColor(RgbColor.fromArgbInt(params.backgroundColor));
                layoutCookie.setBackground(shapeElement);
            }

            int padding = ScreenUtils.dp2px(getContext(),16);
            L.info("" + padding);
            padding = 100;

            if (layoutGravity == LayoutAlignment.BOTTOM) {
                layoutCookie.setPadding(padding, padding, padding, padding);
            }

//            createInAnim();
//            createOutAnim();
        }
    }

    public long getDuration() {
        return duration;
    }


    private void createInAnim() {

        if (layoutGravity == LayoutAlignment.BOTTOM) {
            slideInAnimation = createAnimatorProperty().moveFromY(100).moveToY(0);
        } else {
            slideInAnimation = createAnimatorProperty().moveFromY(0).moveToY(100);
        }
        slideInAnimation.setDuration(7000);
        slideInAnimation.setTarget(this);
        slideInAnimation.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
                L.info("onEnd");
                new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
                    @Override
                    public void run() {
                        dismiss();
                    }
                }, duration);
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });
        slideInAnimation.start();
    }

    private void createOutAnim() {
        if (layoutGravity == LayoutAlignment.BOTTOM) {
            slideOutAnimation = createAnimatorProperty().moveFromY(ScreenUtils.getScreenHeight(getContext()) - 182).moveToY(ScreenUtils.getScreenHeight(getContext()));
        } else {
            slideOutAnimation = createAnimatorProperty().moveFromY(100).moveToY(0);
        }
        slideOutAnimation.setDuration(700);
        slideOutAnimation.setTarget(this);
    }

    private void dismiss() {
        slideOutAnimation.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {

            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
                destroy();
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });
        slideOutAnimation.start();
    }

    public void destroy() {
        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                ComponentParent parent = getComponentParent();
                if (parent != null && isBoundToWindow()) {
//                    Cookie.this.clearAnimation();
                    ((ComponentContainer) parent).removeComponent(Cookie.this);
                }
            }
        }, 200);
    }
}
